#include "operatordb.h"
#include<QMessageBox>
#include<QDebug>
#include<QSqlQuery>
#include<QStringList>


OperatorDB::OperatorDB(QObject *parent):QObject(parent)
{

    //设置数据库类型
    m_db =QSqlDatabase::addDatabase("QSQLITE");

}

OperatorDB::~OperatorDB()
{
    //析构函数，关闭数据库
    m_db.close();
}

OperatorDB &OperatorDB::getInstance()
{
    static OperatorDB instance;
    return instance;
}

void OperatorDB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("D:\\Code\\CPlusPlus\\CPP_QT_PROJECTS\\OnlineCloudTcpServer\\OnlineCloudTcpServer\\TcpServer\\cloud.db");

    //数据库链接和打开
    if(m_db.open()){
        //查询数据库
        QSqlQuery query;
        query.exec("select * from userInfo");
        while(query.next()){
            QString data =QString("%1,%2,%3").arg(query.value(0).toString(),query.value(1).toString(),query.value(2).toString());
            qDebug()<<data;
        }

    }
    else {
        QMessageBox::critical(NULL,"open database","open database failed");
    }
}

bool OperatorDB::handleRegist(const char *name, const char *pwd)
{

    //判断用户名和密码
    if(NULL==name || NULL==pwd){
        return false;
    }

    //添加数据
    QString sql_regist_str =QString("insert into userInfo (name,pwd) values (\'%1\',\'%2\')").arg(name).arg(pwd);

    qDebug()<<sql_regist_str;

    QSqlQuery query;
    //执行成功 返回 true
    return query.exec(sql_regist_str);
}

bool OperatorDB::handleLogin(const char *name, const char *pwd)
{
    //判断用户名和密码
    if(NULL==name || NULL==pwd){
        return false;
    }

    //添加数据
    QString sql_login_str =QString("select * from userInfo where name =\'%1\' and pwd =\'%2\' and online =0 ").arg(name).arg(pwd);

    qDebug()<<sql_login_str;

    QSqlQuery query;
    //执行成功 返回 true

    query.exec(sql_login_str);

    //数据库只会返回一条记录，查询失败，返回false，否则返回为真,记录保存在query 对象中
    if(query.next())
    {
        //更新在线状态
        QString sql_update_str =QString("update userInfo set online = 1 where name =\'%1\' and pwd =\'%2\' ").arg(name).arg(pwd);
        QSqlQuery query;
        //执行成功 返回 true
        query.exec(sql_update_str);
        return true;
    }
    else {
        return false;
    }

}

void OperatorDB::handleOffline(const char *name)
{
    //判断用户名和密码
    if(NULL==name){
        return;
    }

    //更新在线状态
    QString sql_update_str =QString("update userInfo set online = 0 where name =\'%1\' ").arg(name);
    QSqlQuery query;
    //执行成功 返回 true
    query.exec(sql_update_str);

}

QStringList OperatorDB::handleAllOnline()
{
    //更新在线状态
    QString sql_select_str =QString("select name from userInfo where online = 1");
    QSqlQuery query;
    //执行成功 返回 true
    query.exec(sql_select_str);

    QStringList result;
    result.clear();

    while(query.next()){
        result.append(query.value(0).toString());
    }

    return result;


}
